// miniprogram/pages/turntable/turntable.js
const app=getApp()
const db = wx.cloud.database()
const userDB = db.collection('user')
const _ = db.command
Page({
  data: {
    // userInfo: {},
    // hasUserInfo: false,
    // canIUseGetUserProfile: false,
    needGetUserInfo:false,
    loading:true,
    allUserInfo:null,
  },
  onLoad: function (options) {
    wx.showLoading({
      title: '幸运loading...',
      mask:true,
    })
    // if (wx.getUserProfile) {
    //   this.setData({
    //     canIUseGetUserProfile: true
    //   })
    // }

    wx.cloud.callFunction({
      name: 'login',
      complete: res => {
        this.getUserData(res.result.openid)
      }
    })
  },
  getUserData(openid){
    console.log(openid)
    app.globalData.openId=openid
    userDB.where({_openid:openid}).get().then(res => {
      console.log(res.data)
      if(res.data.length==0){
        userDB.add({
          data: {
            description: `用户${openid}`,
            lastVisitDate: new Date(),
            openId:openid,
            userInfo:{
              nickName:'',
              gender:'',
              country:'',
              language:'',
              province:'',
              city:'',
              area:'',
              street:'',
              phoneNumber:'',
              avatarUrl:'',
            },
            gameInfo:{
              todayAllow:3,
              addNum:0,
            },
            orderInfo:[],
          }
        }).then(res => {
          console.log(res)
          if(res._id){
            this.getUserData(openid)
          }
        })
      }
      if(res.data.length>0&&res.data[0].userInfo.nickName==''){
        this.setData({
          needGetUserInfo:true
        })
      }else{
        this.setData({
          needGetUserInfo:false
        })
      }
      this.setData({
        loading:false,
      })
      wx.hideLoading()
      app.globalData.allUerInfo=res.data[0]
      this.setData({
        allUserInfo:res.data[0]
      })
      console.log(app.globalData)
    })
  },
  onReady: function () {

  },
  onShow: function () {

  },
  onHide: function () {

  },
  onUnload: function () {

  },
  onPullDownRefresh: function () {

  },
  onReachBottom: function () {

  },
  onShareAppMessage: function () {

  },
  getUserProfile(e) {
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        if(res.userInfo){
          let userInfo=res.userInfo
          userDB.where({_openid:app.globalData.openId}).update({
            data:{
              userInfo:{
                ...userInfo
              }
            },
            success:res=>{
              console.log(res)
              this.getUserData(app.globalData.openId)
            }
          })
        }
      }
    })
  },
})